var connect = require('connect');  //创建连接
var bodyParser = require('body-parser');   //body解析
var serveStatic = require('serve-static');   //目录访问（静态文件访问）
let map = new Map();
let myarr = new Array();
let psize = 5;

//MAP转为对象
function strMapToObj(strMap){
	let arr =[];
	for(let [k,v] of strMap) {
		let obj ={};
		obj.key = k;
		obj.value = v;
		arr.push(obj);
	}
	return arr;
};
//转为json字符串
function strMapToJson(strMap){
	return JSON.stringify(strMapToObj(strMap));
};
var app = connect()
    .use(bodyParser.json())   //JSON解析
    .use(bodyParser.urlencoded({extended: true}))
    .use(serveStatic(__dirname))
	//use()方法还有一个可选的路径字符串，对传入请求的URL的开始匹配。
	//use方法来维护一个中间件队列
	.use(function (req, res, next) {
		//跨域处理
		// Website you wish to allow to connect
        res.setHeader('Access-Control-Allow-Origin', '*');  //允许任何源
        // Request methods you wish to allow
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');  //允许任何方法
        // Request headers you wish to allow
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token');   //允许任何类型
		res.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"});    //utf-8转码
		next();  //next 方法就是一个递归调用
	})
	.use('/list/add', function(req, res, next) {
		let item = req.body.item;
		console.log(item);
		if(item != undefined){
			console.log('item='+item);
			myarr.unshift(item);
			var data = {"code":200,"msg":"success"};
			console.log('myarr='+myarr);
			res.end(JSON.stringify(myarr));
			next();
		}

		
	})
	.use('/list/page', function(req, res, next) {
		let num = req.body.num
		let psize = req.body.psize
		let start = psize * num - psize;
		let end = start + psize;
		let currentPageResult = myarr.slice(start,end);
		let total_page = (myarr.length / psize).toFixed(0);
		if(total_page == 0){
			total_page = 1;
		}

		console.log('pageNum='+num)

		let page = {
			total_page:total_page,
			current_page_content:currentPageResult
		}

		console.log(JSON.stringify(page));

        res.end(JSON.stringify(page));
		next();
	})
	.use('/list/delete', function(req, res, next) {
		let delName = req.body.itemName;
		console.log("delName="+delName);
		myarr.filter((cur,index)=>{
			if(cur.itemName == delName){
				myarr.splice(index,index+1);
			}
		});

		var data = {"code":200,"msg":"success"};
        res.end(JSON.stringify(data));

		next();
	})
	.use('/list/load', function(req, res, next) {
		console.log('load name='+req.body.name);
		let val = map.get(req.body.name);
		let o = {'name':req.body.name,'message':val};
        res.end(JSON.stringify(o));
		next();
	})
    .listen(3000);
console.log('Server started on port 3000.');